﻿using adb;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Linq;
using Z.EntityFramework.Plus;
using Masuit.Tools.Security;
using System.Collections.Generic;
using PowerStation.RequestModel;
using Microsoft.EntityFrameworkCore;
using adb.excel;
using System.IO;
using System;
using Microsoft.AspNetCore.Authorization;

namespace PowerStation.Controllers
{
    /// <summary>
    /// 账号管理
    /// </summary>
    public class UserController : BaseApi<UserController>
    {
        /// <summary>
        /// 添加员工
        /// </summary>
        /// <param name="content"></param>
        public UserController(IHttpContextAccessor content) : base(content)
        {
        }

        /// <summary>
        /// 创建账号
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultApi<long>> UserCreate(tUser model)
        {
            model.userId = 0;
            if (string.IsNullOrWhiteSpace(model.password)) return ResultApi.error<long>(0, "密码不能为空");
            if (await this._db.tUser.AnyAsync(x => x.account == model.account || x.phone == model.account || x.phone == model.phone || x.account == model.phone)) return ResultApi.error<long>(0, "账号或手机号被使用了");
            model.password = model.password.MDString();
            model.dataState = 2;
            await this._db.tUser.AddAsync(model);
            await this._db.SaveChangesAsync();
            return ResultApi.okOrError(model.userId > 0, model.userId);
        }


        /// <summary>
        /// 账号修改,密码有值就是修改密码
        /// </summary>
        [HttpPut]
        public async Task<ResultApi<bool>> UserModify(tUser model)
        {
            if (await this._db.tUser.AnyAsync(x => x.userId != model.userId && (x.phone == model.phone || x.account == model.phone))) return ResultApi.error<bool>(false, "手机号被使用了");
            if (string.IsNullOrWhiteSpace(model.password))
            {
                model.password = this._db.tUser.Where(x => x.userId == model.userId).Select(x => x.password).FirstOrDefault();
            }
            else
            {
                model.password = model.password.MDString();
            }

            int count = await this._db.tUser.Where(x => x.userId == model.userId).UpdateAsync(x => new tUser()
            {
                phone = model.phone,
                sex = model.sex,
                userName = model.userName,
                password = model.password
            });
            await this._db.SaveChangesAsync();
            return ResultApi.okOrError<bool>(count == 1, count == 1);

        }


        /// <summary>
        /// 用户详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<tUser>> Detail(decimal? userId)   
        {
            if (userId.HasValue == false) userId = this.userId;
            return ResultApi.ok<tUser>(await this._db.tUser.FirstOrDefaultAsync(x=>x.userId == userId));
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        [HttpGet]
        public async Task<ResultApi<List<vUser>>> UserList([FromQuery] RequestMultipleSearchModel model)
        {
            IQueryable<vUser> q = this._db.vUser;
            foreach (var item in model.searchItem)
            {
                if (item.typeName == "用户姓名")
                {
                    q = q.Where(x => x.userName.Contains(item.value));
                }
                else if (item.typeName == "登录账号")
                {
                    q = q.Where(x => x.account.Contains(item.value));
                }
            }
            var result = await model.setPageAsync(q);
            return ResultApi.ok<List<vUser>>(await result.Item2.ToListAsync(), result.Item1);
        }


        /// <summary>
        /// 删除账号
        /// </summary>
        [HttpDelete]
        public async Task<ResultApi<bool>> UserDelete(List<decimal> userIds)
        {

            using (var tran = await this._db.Database.BeginTransactionAsync())
            {
                var deleteList = await this._db.tUser.Where(x => userIds.Contains(x.userId)).ToListAsync();
                foreach (var item in deleteList)
                {
                    item.dataState = 1;
                    item.account += "_" + DateTime.Now.ToString();
                }
                await this._db.SaveChangesAsync();
                await tran.CommitAsync();
            }
            return ResultApi.okOrError<bool>(true, true);
        }


        /// <summary>
        /// 冻结账号
        /// </summary>
        /// <param name="enbale">是否启用</param>
        /// <param name="userIds">账号ID</param>
        [HttpPut]
        public async Task<ResultApi<bool>> UserEnableModify(List<decimal> userIds,bool enbale)
        {
            int count = await this._db.tUser.Where(x => userIds.Contains(x.userId)).UpdateAsync(x => new tUser { 
                dataState = enbale?0:2,
            });
            if(count == userIds.Count)
                await this._db.SaveChangesAsync();
            return ResultApi.okOrError<bool>(count == userIds.Count, count == userIds.Count);
        }


        /// <summary>
        /// 导入用户信息,只支持新版本的xls,返回的数据中,userId 大于等于 0表示能创建,userId 小于 0表示不能创建,password存放不能创建的由
        /// </summary>
        [HttpPost]
        public async Task<ResultApi<List<tUser>>> UserExcelCreate([FromForm] RequestUserExcelModel model)
        {
            if (model.xlsFile.Length > 0)
            {
                var titles = await this._db.tExcelTitle.Where(x=>x.excelType == 2).ToListAsync();
                if (titles.Count > 0)
                {
                    
                    Task<List<tUser>> task = new Task<List<tUser>>(() =>
                    {
                        using (var stream = new MemoryStream())
                        {
                            model.xlsFile.CopyTo(stream);
                            return ExcelExport.inputData<tUser>(titles, stream);
                        }
                    });
                    task.Start();
                    var lst = await task;
                    if (lst.Count == 0) return ResultApi.error<List<tUser>>(null, "未读取到数据,请核对格式");
                    //判断不能注册的
                    var NotCreateLst = lst.Where(x => lst.Any(k => k != x && (x.account == k.account || x.account == k.phone || x.phone == k.account || x.phone == k.phone))).Select(x =>
                    {
                        x.password = "数据中存在账号或手机号重复";
                        x.userId = -1;
                        return x;
                    }).ToList();
                    //已经有账号的
                    Task<List<tUser>> checkAccountFromDb = new Task<List<tUser>>(() =>
                    {
                        return lst.Where(x => x.userId > -1 && this._db.tUser.Any(k => x.account == k.account || x.account == k.phone || x.phone == k.account || x.phone == k.phone)).Select(x =>
                        {
                            if (string.IsNullOrEmpty(x.password))
                                x.password = "账号已存在系统中";
                            x.userId = -1;
                            return x;
                        }).ToList();
                    });
                    checkAccountFromDb.Start();
                    var HasAccountLst = await checkAccountFromDb;
                    //能创建的账号
                    var OkCreateLst = lst.Where(x => x.userId > -1).Select(x =>
                    {
                        x.password = model.password.MDString();
                        x.userId = 0;
                        return x;
                    }).ToList();


                    if (model.isCreate)
                    {
                        await this._db.tUser.AddRangeAsync(lst.Where(x => x.userId == 0).ToList());
                        await this._db.SaveChangesAsync();
                    }
                    return ResultApi.ok(lst);
                }
            }
            return ResultApi.okOrError<List<tUser>>(false, default(List<tUser>), "文件未上传");
        }


        /// <summary>
        /// 绑定电站
        /// </summary>
        /// <param name="model">绑定数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultApi<bool>> BindPowerStation(RequestBindPowerStationModel model)
        {
            int count = await this._db.tPowerStation.Where(x => x.dataState == 0 && model.powerStationIds.Contains(x.powerStationId)).CountAsync();
            if (count != model.powerStationIds.Count) return ResultApi.error(false, "电站数据异常,请检查是否每个电站都存在");
            if (!(await this._db.tUser.AnyAsync(x => x.userId == model.userId && x.dataState == 0))) return ResultApi.error(false, "被操作账号异常");

            using (var tran = await this._db.Database.BeginTransactionAsync())
            {
                await this._db.tUserPowerStation.Where(x => x.ups_user_userId_fk == model.userId).DeleteAsync();
                await this._db.SaveChangesAsync();
                await this._db.tUserPowerStation.AddRangeAsync(model.powerStationIds.Select(x=>new tUserPowerStation() {
                    ups_powerStation_powerStationId_fk = x,
                    ups_user_userId_fk = model.userId,
                }));
                await this._db.SaveChangesAsync();
                tran.Commit();
            }
            return ResultApi.okOrError<bool>(true, true);
        }

        /// <summary>
        /// 返回绑定的账号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tUserPowerStation>>> BindPowerStationList(decimal userId)
        {
            IQueryable<tUserPowerStation> q = this._db.tUserPowerStation.Where(x=>x.ups_user_userId_fk == userId);
            return ResultApi.ok<List<tUserPowerStation>>(await q.ToListAsync()); ;
        }

        /// <summary>
        /// 返回账号所在角色表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tUserRole>>> RoleList()
        {
            IQueryable<tUserRole> q = this._db.tUserRole;
            return ResultApi.ok<List<tUserRole>>(await q.Where(x=>x.userPermission_userId_fk == this.userId).ToListAsync(), 0);
        }


        /// <summary>
        /// 返回角色权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<vUserPermission>>> UserPermissionList()
        {
            IQueryable<vUserPermission> q = this._db.vUserPermission.Where(x=>x.userId == this.userId);
            return ResultApi.ok<List<vUserPermission>>(await q.ToListAsync(),0);
        }


        /// <summary>
        /// 记录手机推送id
        /// </summary>
        /// <param name="deviceId">个推ID</param>
        [HttpPut]
        public async Task<ResultApi<bool>> PhoneDevice(string deviceId)
        {
            using (var tran = await this._db.Database.BeginTransactionAsync())
            {
                await this._db.tUserDeviceSN.Where(x => x.phoneSN == deviceId).DeleteAsync();
                await this._db.SaveChangesAsync();
                await this._db.tUserDeviceSN.AddAsync(new tUserDeviceSN { phoneDevice_userId_fk = this.userId,phoneSN = deviceId});
                await this._db.SaveChangesAsync();

                tran.Commit();
            }
            return ResultApi.okOrError<bool>(true, true);
        }

    }
}
